package main

import (
	"crypto/sha256"
	"database/sql"
	"encoding/hex"
	"errors"
	"time"
)

type traBlock struct {
	//储存多个交易记录，消息序号对应消息摘要
	//messageList map[string]string
	message string
	//时间戳
	timestamp int64
	//当前区块的哈希值
	hash string
	//上一区块的哈希值
	prevHash string
	//序列号，用于查询
	EventID int64
	//地址
	srcAddress string
	dstAddress string
}

//新建区块
func NewTraBlock(digest ,srcAdd, dstAdd string, EventID int64) *traBlock {
	b := new(traBlock)
	b.message = digest
	b.EventID = EventID
	b.srcAddress = srcAdd
	b.dstAddress = dstAdd
	b.timestamp = time.Now().UnixNano()
	return b
}

//链接上下区块
func (b *traBlock)LinkBTrf(db *sql.DB){
	//log.Println(b.EventID)
	if preHash := NowBTrfHash(db, b.EventID); preHash != ""{
	//	log.Println(preHash)
		b.prevHash = preHash
	}
}

func (b *traBlock)LinkBrTrf(db *sql.DB){
	//log.Println(b.EventID)
	if preHash := NowBrTrfHash(db, b.EventID); preHash != ""{
		//log.Println(preHash)
		b.prevHash = preHash
	}
}

//封装区块
func (b *traBlock)Seal() {
	b.timestamp = time.Now().UnixNano()
	b.hash = b.HashBlock()
}

//获取区块的hash值
func (b *traBlock)HashBlock()(h string)  {
	message := b.prevHash
	message = message + b.message
	msgHash := sha256.Sum256([]byte(message))
	//进行十六进制字符串编码
	h = hex.EncodeToString(msgHash[:])
	return
}

//验证区块
func (b *traBlock)Validate(){
	if b.hash != b.HashBlock(){
		err := errors.New("交易数据被修改")
		panic(err)
	}
}


